
package org.spring.config.server.listener;

import java.sql.SQLException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebListener
public class ConfigServletContextListener implements ServletContextListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Server localServer;

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        logger.info("liting: contextDestroyed");
        if (this.localServer != null) {
            this.localServer.stop();
            this.localServer = null;
        }
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        logger.info("liting: contextInitialized");
        startH2Server();
    }

    private void startH2Server() {
        try {
            if (localServer == null) {
                localServer = Server.createTcpServer(new String[] {"-tcpPort", "9095", "-tcpAllowOthers"}).start();
                if (localServer.isRunning(true)) {
                    logger.info("H2 server was started and is running.");
                } else {
                    throw new RuntimeException("Could not start H2 server.");
                }
            }
        } catch (SQLException localSQLException) {
            throw new RuntimeException("Failed to start H2 server: ", localSQLException);
        }
    }

}
